<template>
  <div class="login-container">
    <h2 class="login-title">{{ TITLE }}</h2>
    <a-form class="login-form">
      <a-form-item style="margin-top: 10px" v-bind="validateInfos.username">
        <a-input
          class="inputBox"
          v-model:value="modelRef.username"
          placeholder="请输入用户名"
          @keyup.enter.prevent="handleLogin"
        >
          <template #prefix>
            <img :src="User" alt="" />
          </template>
        </a-input>
      </a-form-item>
      <a-form-item v-bind="validateInfos.password">
        <a-input-password
          class="inputBox"
          v-model:value="modelRef.password"
          placeholder="请输入密码"
          @keyup.enter.prevent="handleLogin"
        >
          <template #prefix>
            <img :src="Password" alt="" />
          </template>
        </a-input-password>
      </a-form-item>
      <a-form-item v-bind="validateInfos.code">
        <a-input
          class="inputBox"
          v-model:value="modelRef.code"
          placeholder="请输入验证码"
          @keyup.enter.prevent="handleLogin"
        >
          <template #prefix>
            <img :src="Captcha" alt="" />
          </template>
          <template #suffix>
            <img class="code-img" :src="codeUrl" @click="getCode" />
          </template>
        </a-input>
      </a-form-item>
      <a-checkbox v-model:checked="modelRef.rememberMe" style="margin: 0 0 25px 0; color: white"
        >记住我</a-checkbox
      >
      <a-form-item>
        <a-button class="submit" type="primary" @click.prevent="handleLogin">登录</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts">
  import { defineComponent, reactive, toRaw, ref, onMounted } from 'vue';
  import { Form } from 'ant-design-vue';
  import User from '/images/user.png';
  import Password from '/images/password.png';
  import Captcha from '/images/captcha.png';
  import { getCodeImgApi } from '/@/api/user';
  import { useUserStore } from '/@/store/modules/user';
  import { rsaEncryption } from '/@/utils/cipher';
  import { TITLE, REMEMBERME_KEY } from '/@/setting';
  import { createLocalStorage } from '../utils/cache';

  const useForm = Form.useForm;
  const userStore = useUserStore();
  export default defineComponent({
    setup() {
      const modelRef = reactive({
        username: 'admin',
        password: '123456',
        rememberMe: false,
        code: '',
        uuid: '',
      });

      const rulesRef = reactive({
        username: [
          {
            required: true,
            message: '用户名不能为空',
          },
        ],
        password: [
          {
            required: true,
            message: '密码不能为空',
          },
        ],
        code: [
          {
            required: true,
            message: '验证码不能为空',
          },
        ],
      });

      const { resetFields, validate, validateInfos } = useForm(modelRef, rulesRef);

      const ls = createLocalStorage({ timeout: null });

      const handleLogin = async () => {
        try {
          await validate();
          const user = {
            ...toRaw(modelRef),
          };
          if (user.password !== cookiePass.value) {
            user.password = rsaEncryption.encryptByRSA(user.password);
          }
          if (user.rememberMe) {
            ls.set(REMEMBERME_KEY, {
              username: user.username,
              password: user.password,
              rememberMe: user.rememberMe,
            });
          } else {
            ls.remove(REMEMBERME_KEY);
          }
          if (!(await userStore.LoginAction(user))) {
            getCode();
          }
        } catch (error) {
          console.log('error', error);
        }
      };

      const codeUrl = ref<String>('');
      const getCode = async () => {
        const { img, uuid } = await getCodeImgApi();
        codeUrl.value = img;
        modelRef.uuid = uuid;
      };

      const cookiePass = ref<String>('');
      const getCookie = () => {
        let obj = ls.get(REMEMBERME_KEY);
        let username = obj?.username;
        let password = obj?.password;
        let rememberMe = obj?.rememberMe;
        // 保存cookie里面的加密后的密码
        cookiePass.value = password === undefined ? '' : password;
        modelRef.username = username === undefined ? modelRef.username : username;
        modelRef.password = password === undefined ? modelRef.password : password;
        modelRef.rememberMe = rememberMe === undefined ? false : Boolean(rememberMe);
      };

      onMounted(() => {
        getCode();
        getCookie();
      });

      return {
        TITLE,
        User,
        Password,
        Captcha,
        validateInfos,
        resetFields,
        modelRef,
        handleLogin,
        getCode,
        codeUrl,
      };
    },
  });
</script>
<style lang="less" scoped>
  /* 背景 */
  .login-container {
    position: absolute;
    width: 100%;
    height: 100%;
    min-width: 600px;
    background: url('/images/login-bg.png');
  }

  .login-title {
    color: #fff;
    text-align: center;
    margin: 138px 0;
    font-size: 48px;
    font-family: Microsoft Yahei;
  }

  .login-form {
    width: 565px;
    height: 372px;
    margin: 0 auto;
    background: url('/images/login-form-bg.png');
    padding: 40px 110px;
  }

  /* 输入框 */
  .inputBox {
    height: 42px;
  }

  /* 登陆按钮 */
  .submit {
    width: 100%;
    height: 45px;
  }

  .code-img {
    cursor: pointer;
    vertical-align: middle;
  }
</style>
